<?php

namespace App\Http\Controllers\Firm;

use App\Events\Rank;
use App\Http\Controllers\BaseController;
use App\Models\Message;
use App\Rules\Code;
use Illuminate\Http\Request;
use App\Models\FirmMessage;
use Illuminate\Support\Facades\DB;

class MessageController extends BaseController
{
    public function store(Request $request)
    {
        $param = $this->validate($request,[
            'name' => 'required|max:30',
            'sex' => 'required|in:1,2',
            'content' => 'required|max:600',
            'firm_id' => 'required|integer',
            'category_id' => 'required|in:1,2',
            'code' => ['required',new Code()]
        ]);

        $param['user_id'] = auth('api')->id();

        $mes = FirmMessage::query()->create($param);

        if($mes->getKey()){
            $auth = DB::table('users')->where('id',$param['user_id'])->value('auth');

            if ($auth==1){
                $name = DB::table('user_auths')->where('user_id',$param['user_id'])->value('name');
            }else{
                $name = DB::table('firms')->where('user_id',$param['user_id'])->value('corporate_name');
            }

            $company_name = DB::table('firms')->where('id',$param['firm_id'])->value('name');

            $type = 2;

            $message = $name .'咨询了'.$company_name.'公司';
            if ($param['category_id']==1){
                $type=7;
                $message = $name.'成功申请加盟了'.$company_name.'酒店品牌';
            }

            Message::query()->create([
                'type' => $type,
                'content' => $message
            ]);


            return $this->success('留言成功');

        }

        return $this->success('留言失败');
    }
}
